import axios from 'axios';

// Crear instancia de axios con configuración base
const api = axios.create({
  baseURL: process.env.VUE_APP_API_URL || 'http://localhost:8080/api', // 直接指向后端API
  timeout: 10000,
  withCredentials: true, // 添加跨域请求凭证支持
  headers: {
    'Content-Type': 'application/json'
  }
});

// Interceptor para añadir token a las solicitudes
api.interceptors.request.use(
  config => {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
    if (userInfo.token) {
      config.headers['Authorization'] = `Bearer ${userInfo.token}`;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// Interceptor para manejar respuestas y errores
api.interceptors.response.use(
  response => {
    // 处理Spring Boot后端返回的标准响应格式
    const data = response.data;

    // 如果data本身就是标准格式（包含success, message, data字段）
    if (data && typeof data === 'object' && 'success' in data) {
      return {
        code: response.status,
        success: data.success,
        message: data.message,
        data: data.data
      };
    }

    // 如果data是直接的数据（不包含封装），直接返回
    return {
      code: response.status,
      success: true,
      message: '',
      data: data
    };
  },
  error => {
    // Manejar errores de respuesta
    const { status, data } = error.response || {};

    // 带有错误信息的响应
    if (data && typeof data === 'object' && 'error' in data) {
      console.error('API Error:', data.error);
    }

    // Si es un error de autenticación
    if (status === 401) {
      // Limpiar información de usuario
      localStorage.removeItem('userInfo');
      // Redireccionar a login (debes implementar esta lógica donde uses este servicio)
    }

    return Promise.reject(error);
  }
);

// API de autenticación
export const authAPI = {
  login(username, password) {
    return api.post('/users/login', { username, password });
  },
  register(userData) {
    return api.post('/users/register', userData);
  },
  getUserInfo(id) {
    return api.get(`/users/${id}`);
  }
};

// API para usuarios
export const userAPI = {
  // 获取用户基本信息
  getUserInfo() {
    return api.get('/users/profile');
  },

  // 更新用户基本信息
  updateUserInfo(data) {
    return api.put('/users', data);
  },

  // 修改密码
  changePassword(data) {
    return api.put('/users/password', data);
  },

  // 获取通知设置
  getNotificationSettings() {
    return api.get('/users/notification-settings');
  },

  // 更新通知设置
  updateNotificationSettings(data) {
    return api.put('/users/notification-settings', data);
  },

  // 获取种植户详细信息
  getFarmerInfo() {
    return api.get('/farmers/current');
  },

  // 更新种植户信息
  updateFarmerInfo(data) {
    return api.put('/farmers', data);
  },

  // 获取经销商详细信息
  getDealerInfo() {
    return api.get('/dealers/current');
  },

  // 更新经销商信息
  updateDealerInfo(data) {
    return api.put('/dealers', data);
  },

  // 获取经销商配送设置
  getDealerDeliverySettings() {
    return api.get('/dealers/delivery-settings');
  },

  // 更新经销商配送设置
  updateDealerDeliverySettings(data) {
    return api.put('/dealers/delivery-settings', data);
  },

  // 添加用户列表查询方法
  getUserList(params) {
    console.log('正在请求用户列表:', params);
    return api.get('/users', { params });
  },

  // 添加用户
  addUser(data) {
    return api.post('/users', data);
  },

  // 更新用户
  updateUser(data) {
    return api.put(`/users/${data.id}`, data);
  },

  // 删除用户
  deleteUser(id) {
    return api.delete(`/users/${id}`);
  },

  // 重置密码
  resetPassword(data) {
    return api.put(`/users/${data.id}/password`, { password: data.password });
  },

  // 更新用户状态
  updateUserStatus(id, status) {
    return api.put(`/users/${id}/status`, { isActive: status });
  },

  // 个人修改密码
  updatePassword(data) {
    return api.put('/users/password', data);
  },

  // 上传头像
  uploadAvatar(formData) {
    return api.post('/users/avatar', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
  },

  // 发送验证码
  sendVerificationCode(params) {
    return api.post('/users/verification-code', params);
  },

  // 更新绑定信息
  updateBinding(params) {
    return api.put('/users/binding', params);
  },

  // 解绑微信
  unbindWechat() {
    return api.delete('/users/binding/wechat');
  }
};

// API para agricultores (farmers)
export const farmerAPI = {
  getFarmers(params) {
    return api.get('/farmers', { params });
  },
  getFarmerById(id) {
    return api.get(`/farmers/${id}`);
  },
  addFarmer(data) {
    return api.post('/farmers', data);
  },
  updateFarmer(data) {
    return api.put('/farmers', data);
  },
  deleteFarmer(id) {
    return api.delete(`/farmers/${id}`);
  },
  // Agregar métodos específicos
  countFarmers() {
    return api.get('/farmers/count');
  },
  countTodayNewFarmers() {
    return api.get('/farmers/count/today');
  },
  countFarmersByProvince() {
    return api.get('/farmers/count/province');
  },
  updateVerificationStatus(id, status, remark) {
    return api.put(`/farmers/${id}/verification-status`, { status, remark });
  }
};

// API para distribuidores (dealers)
export const dealerAPI = {
  getDealers(params) {
    return api.get('/dealers', { params });
  },
  getDealerById(id) {
    return api.get(`/dealers/${id}`);
  },
  addDealer(data) {
    return api.post('/dealers', data);
  },
  updateDealer(data) {
    return api.put('/dealers', data);
  },
  deleteDealer(id) {
    return api.delete(`/dealers/${id}`);
  }
};

// API para productos
export const productAPI = {
  getProducts(params) {
    return api.get('/products', { params });
  },
  getProductById(id) {
    return api.get(`/products/${id}`);
  },
  addProduct(path, data) {
    return api.post(`/products${path}`, data);
  },
  updateProduct(path, data) {
    return api.put(`/products${path}`, data);
  },
  deleteProduct(id) {
    return api.delete(`/products/${id}`);
  },
  countProduct() {
    return api.get('/products/count');
  },
  countTodayNewProduct() {
    return api.get('/products/count/today');
  },
  countProductByCategory() {
    return api.get('/products/count/category');
  },
  getProcessingInfo(id) {
    return api.get(`/products/processing/${id}`);
  },
  getProcessingInfoByBatchId(batchId) {
    return api.get(`/products/processing/batch/${batchId}`);
  },
  // 获取产品产量排行
  getProductYieldRanking(timeRange) {
    return api.get('/products/yield-ranking', { params: { timeRange } });
  }
};

// API para códigos de trazabilidad
export const traceInfoAPI = {
  getTraceInfoList(params) {
    return api.get('/trace-info', { params });
  },
  getTraceInfoById(id) {
    return api.get(`/trace-info/${id}`);
  },
  getTraceInfoByCode(code) {
    return api.get(`/trace-info/code/${code}`);
  },
  generateTraceCode(data) {
    return api.post('/trace-info/generate', data);
  },
  // 添加与前端调用一致的方法名
  generateTraceInfo(data) {
    return api.post('/trace-info/generate', data);
  },
  downloadTraceInfo(id) {
    return api.get(`/trace-info/${id}/download`);
  },
  deleteTraceInfo(id) {
    return api.delete(`/trace-info/${id}`);
  },
  countTraceCode() {
    return api.get('/trace-info/count');
  },
  countTodayNewTraceCode() {
    return api.get('/trace-info/count/today');
  }
};

// API para consultas de trazabilidad
export const traceQueryAPI = {
  queryTrace(code) {
    return api.get(`/trace-info/query/${code}`);
  },
  recordQuery(data) {
    return api.post('/trace-stats/record', data);
  },
  getTraceQueryLogs(params) {
    return api.get('/trace-stats/logs', { params });
  },
  countTraceQuery() {
    return api.get('/trace-stats/count');
  },
  countTodayTraceQuery() {
    return api.get('/trace-stats/count/today');
  },
  countQueryByLocation() {
    return api.get('/trace-stats/count/location');
  },
  countTopQueriedProducts(limit = 10) {
    return api.get('/trace-query/top-products', { params: { limit } });
  },
  // 添加获取查询趋势数据的API
  getQueryTrend(period = '7') {
    // 确保period是数字字符串，如果是week/month等字符串，转换为对应的天数
    let days = period;
    if (period === 'week') days = '7';
    if (period === 'month') days = '30';
    if (period === 'quarter') days = '90';

    return api.get('/trace-stats/query-trend', { params: { days } });
  },
  // 添加获取设备分布数据的API
  getDeviceDistribution() {
    return api.get('/trace-stats/device-distribution');
  }
};

// API para pedidos
export const orderAPI = {
  getOrders(params) {
    return api.get('/orders', { params });
  },
  getOrderById(id) {
    return api.get(`/orders/${id}`);
  },
  createOrder(data) {
    return api.post('/orders', data);
  },
  updateOrder(data) {
    return api.put('/orders', data);
  },
  deleteOrder(id) {
    return api.delete(`/orders/${id}`);
  },
  shipOrder(id, logisticsData) {
    return api.put(`/orders/${id}/ship`, logisticsData);
  },
  completeOrder(id) {
    return api.put(`/orders/${id}/complete`);
  },
  cancelOrder(id) {
    return api.put(`/orders/${id}/cancel`);
  },
  countOrder() {
    return api.get('/orders/count');
  },
  countTodayNewOrder() {
    return api.get('/orders/count/today');
  },
  countOrderByStatus() {
    return api.get('/orders/count/status');
  },
  countOrderLast7Days() {
    return api.get('/orders/count/last7days');
  }
};

// API para clientes
export const customerAPI = {
  getCustomers(params) {
    return api.get('/customers', { params });
  },
  getCustomerById(id) {
    return api.get(`/customers/${id}`);
  },
  addCustomer(data) {
    return api.post('/customers', data);
  },
  updateCustomer(data) {
    return api.put('/customers', data);
  },
  deleteCustomer(id) {
    return api.delete(`/customers/${id}`);
  }
};

// API para estadísticas
export const statisticsAPI = {
  getSystemOverview() {
    return api.get('/statistics/overview');
  },
  getLast7DaysStatistics() {
    return api.get('/statistics/last7days');
  },
  getUserRoleDistribution() {
    return api.get('/statistics/user-roles');
  },
  getProductCategoryDistribution() {
    return api.get('/statistics/product-categories');
  },
  getFarmerProvinceDistribution() {
    return api.get('/statistics/farmer-provinces');
  },
  getDealerProvinceDistribution() {
    return api.get('/statistics/dealer-provinces');
  },
  getOrderStatusDistribution() {
    return api.get('/statistics/order-statuses');
  },
  getTraceQueryLocationDistribution() {
    return api.get('/statistics/trace-query-locations');
  },
  getTopQueriedProducts(limit = 10) {
    return api.get('/statistics/top-queried-products', { params: { limit } });
  },
  getDateRangeStatistics(startDate, endDate) {
    return api.get('/statistics/date-range', {
      params: {
        startDate,
        endDate
      }
    });
  },
  // 添加种植户统计数据API
  getFarmerStats(farmerId) {
    return api.get(`/statistics/farmer/${farmerId}`);
  },
  // 添加种植户待办事项API
  getFarmerTodos(farmerId) {
    return api.get(`/statistics/farmer/${farmerId}/todos`);
  },
  // 获取种植户超时待办事项API
  getOverdueTodos(farmerId) {
    return api.get(`/statistics/farmer/${farmerId}/overdueTodos`);
  },
  // 更新种植户待办事项API
  updateFarmerTodos(farmerId, todoItems) {
    return api.put(`/statistics/farmer/${farmerId}/todos`, todoItems);
  },
  // 经销商仪表盘需要的方法
  // 获取经销商统计数据
  getDealerStats() {
    return api.get('/statistics/dealer/stats');
  },
  // 获取经销商销售数据
  getDealerSalesData(period = 'week') {
    return api.get('/statistics/dealer/sales', { params: { period } });
  },
  // 获取经销商产品分布
  getDealerProductDistribution() {
    return api.get('/statistics/dealer/products');
  },
  // 获取经销商待办事项
  getDealerTodoTasks(dealerId) {
    return api.get(`/statistics/dealer/${dealerId}/todos`);
  },
  // 获取统计数据
  getStats() {
    return api.get('/statistics/overview');
  },
  // 获取最近订单
  getRecentOrders() {
    return api.get('/statistics/recent-orders');
  },
  // 获取产品分布
  getProductDistribution() {
    return api.get('/statistics/product-distribution');
  },
  // 获取待办任务
  getTodoTasks() {
    return api.get('/statistics/todo-tasks');
  }
};

// API para estadísticas del agricultor (Farmer Stats API)
export const statsAPI = {
  // 获取农户统计数据
  getFarmerStats() {
    return api.get('/stats/farmer');
  },

  // 获取最近活动
  getRecentActivities() {
    return api.get('/stats/activities');
  },

  // 获取作物分布数据
  getCropDistribution() {
    return api.get('/stats/crop-distribution');
  },

  // 获取产量趋势数据
  getYieldTrend() {
    return api.get('/stats/yield-trend');
  }
};

// Dashboard API - 控制面板数据API
export const dashboardAPI = {
  // 获取数据卡片信息
  getDataCards() {
    return api.get('/dashboard/cards');
  },

  // 获取用户分布数据
  getUserDistribution() {
    return api.get('/dashboard/user-distribution');
  },

  // 获取用户注册趋势
  getRegistrationStats(period = 'week') {
    return api.get('/dashboard/registration-stats', {
      params: { period }
    });
  },

  // 获取系统消息
  getSystemMessages() {
    return api.get('/dashboard/system-messages');
  }
};

// API para cultivos
export const farmingAPI = {
  saveFarmingInfo(userId, farmingInfo) {
    return api.post(`/farming/info/user/${userId}`, farmingInfo);
  },
  getFarmingInfoByUserId(userId) {
    return api.get(`/farming/info/user/${userId}`);
  },
  getFarmingInfoById(id) {
    return api.get(`/farming/info/${id}`);
  },
  getFarmingInfoByBatchId(batchId) {
    return api.get(`/farming/info/batch/${batchId}`);
  },
  // 添加获取种植户活动记录API
  getFarmerActivities(farmerId) {
    return api.get(`/farming/activities/${farmerId}`);
  },

  // 新增管理后台所需方法
  // 获取所有种植信息（分页）
  getAllFarmingInfo(params) {
    return api.get('/farming', { params });
  },
  // 更新种植信息
  updateFarmingInfo(id, farmingInfo) {
    return api.put(`/farming/info/${id}`, farmingInfo);
  },
  // 删除种植信息
  deleteFarmingInfo(id) {
    return api.delete(`/farming/info/${id}`);
  },
  // 批量删除种植信息
  batchDeleteFarmingInfo(ids) {
    return api.delete('/farming/info/batch', { data: ids });
  }
};

// API para distribución
export const distributionAPI = {
  saveDistributionInfo(dealerId, distributionInfo) {
    return api.post(`/distribution/entry?dealerId=${dealerId}`, distributionInfo);
  },
  getDistributionInfoByDealerId(dealerId) {
    return api.get(`/distribution/dealer/${dealerId}`);
  },
  getDistributionInfoById(id) {
    return api.get(`/distribution/${id}`);
  },
  getDistributionInfoByBatchId(batchId) {
    return api.get(`/distribution/batch/${batchId}`);
  }
};

// API para códigos de trazabilidad
export const traceCodeAPI = {
  generateTraceCode(batchId) {
    return api.post(`/tracecode/generate?batchId=${batchId}`);
  },
  getTraceCodeInfo(code) {
    return api.get(`/tracecode/${code}`);
  }
};

// API para roles (角色管理)
export const roleAPI = {
  // 获取角色列表
  getRoles(params) {
    return api.get('/roles', { params });
  },
  // 获取角色详情
  getRoleById(id) {
    return api.get(`/roles/${id}`);
  },
  // 添加角色
  addRole(data) {
    return api.post('/roles', data);
  },
  // 更新角色
  updateRole(data) {
    return api.put(`/roles/${data.id}`, data);
  },
  // 删除角色
  deleteRole(id) {
    return api.delete(`/roles/${id}`);
  },
  // 更新角色状态
  updateRoleStatus(id, status) {
    return api.put(`/roles/${id}/status`, { status });
  },
  // 获取角色的权限
  getRolePermissions(roleId) {
    return api.get(`/roles/${roleId}/permissions`);
  },
  // 分配权限
  assignPermissions(roleId, permissionIds) {
    return api.post(`/roles/${roleId}/permissions`, { permissionIds });
  }
};

// API para permisos (权限管理)
export const permissionAPI = {
  // 获取权限列表
  getPermissions(params) {
    return api.get('/permissions', { params });
  },
  // 获取权限树
  getPermissionTree() {
    return api.get('/permissions/tree');
  },
  // 获取权限详情
  getPermissionById(id) {
    return api.get(`/permissions/${id}`);
  },
  // 添加权限
  addPermission(data) {
    return api.post('/permissions', data);
  },
  // 更新权限
  updatePermission(data) {
    return api.put(`/permissions/${data.id}`, data);
  },
  // 删除权限
  deletePermission(id) {
    return api.delete(`/permissions/${id}`);
  }
};

// API para menús (菜单管理)
export const menuAPI = {
  // 获取菜单列表
  getMenus(params) {
    return api.get('/menus', { params });
  },
  // 获取菜单树
  getMenuTree() {
    return api.get('/menus/tree');
  },
  // 获取菜单详情
  getMenuById(id) {
    return api.get(`/menus/${id}`);
  },
  // 添加菜单
  addMenu(data) {
    return api.post('/menus', data);
  },
  // 更新菜单
  updateMenu(data) {
    return api.put(`/menus/${data.id}`, data);
  },
  // 删除菜单
  deleteMenu(id) {
    return api.delete(`/menus/${id}`);
  },
  // 更新菜单状态
  updateMenuStatus(id, status) {
    return api.put(`/menus/${id}/status`, { status });
  }
};

// API para diccionarios (字典管理)
export const dictAPI = {
  // 获取字典类型列表
  getDictTypes(params) {
    return api.get('/dict/types', { params });
  },
  // 获取字典类型详情
  getDictTypeById(id) {
    return api.get(`/dict/types/${id}`);
  },
  // 添加字典类型
  addDictType(data) {
    return api.post('/dict/types', data);
  },
  // 更新字典类型
  updateDictType(data) {
    return api.put(`/dict/types/${data.id}`, data);
  },
  // 删除字典类型
  deleteDictType(id) {
    return api.delete(`/dict/types/${id}`);
  },
  // 获取字典数据列表
  getDictData(typeCode, params) {
    return api.get(`/dict/data/${typeCode}`, { params });
  },
  // 获取字典数据详情
  getDictDataById(id) {
    return api.get(`/dict/data/${id}`);
  },
  // 添加字典数据
  addDictData(data) {
    return api.post('/dict/data', data);
  },
  // 更新字典数据
  updateDictData(data) {
    return api.put(`/dict/data/${data.id}`, data);
  },
  // 删除字典数据
  deleteDictData(id) {
    return api.delete(`/dict/data/${id}`);
  }
};
// API para logs del sistema (系统日志)
export const logAPI = {
  // 获取操作日志
  getOperationLogs: (params) => {
    return api.get('/system/operationLog/list', { params });
  },
  // 导出操作日志
  exportOperationLogs: (params) => {
    return api.get('/system/operationLog/export', { params, responseType: 'blob' });
  },
  // 清空操作日志
  clearOperationLogs: () => {
    return api.delete('/system/operationLog/clear');
  },
  // 获取登录日志
  getLoginLogs: (params) => {
    return api.get('/system/loginLog/list', { params });
  },
  // 导出登录日志
  exportLoginLogs: (params) => {
    return api.get('/system/loginLog/export', { params, responseType: 'blob' });
  },
  // 清空登录日志
  clearLoginLogs: () => {
    return api.delete('/system/loginLog/clear');
  }
};
// 溯源查询API
export const traceAPI = {
  // 通过溯源码查询产品信息
  queryByCode(code) {
    return api.get(`/trace-info/query/${code}`);
  },

  // 记录溯源查询
  recordQuery(data) {
    return api.post('/trace-query/record', data);
  },

  // 获取溯源查询趋势
  getQueryTrend(period = 'week') {
    return api.get('/trace-query/trend', { params: { period } });
  },

  // 获取设备分布
  getDeviceDistribution() {
    return api.get('/trace-query/device-distribution');
  },

  // 获取查询日志
  getQueryLogs(page = 1, size = 10) {
    return api.get('/trace-query/logs', { params: { page, size } });
  },

  // 获取总查询次数
  getQueryCount() {
    return api.get('/trace-query/count');
  },

  // 获取今日查询次数
  getTodayQueryCount() {
    return api.get('/trace-query/count/today');
  },

  // 获取按地区统计的查询次数
  getQueryCountByLocation() {
    return api.get('/trace-query/count/location');
  },

  // 获取查询次数最多的产品
  getTopQueriedProducts(limit = 10) {
    return api.get('/trace-query/top-products', { params: { limit } });
  }
};

// 物流管理API
export const logisticsAPI = {
  // 获取物流列表
  getLogistics(params) {
    console.log('调用获取物流列表API，参数:', params);
    return api.get('/logistics', { params });
  },

  // 获取物流详情
  getLogisticsById(id) {
    console.log('调用获取物流详情API，ID:', id);
    return api.get(`/logistics/${id}`);
  },

  // 发货
  shipOrder(data) {
    console.log('调用发货API，数据:', data);
    return api.post('/logistics/ship', data);
  },

  // 更新物流状态
  updateLogisticsStatus(id, status) {
    console.log('调用更新物流状态API，ID:', id, '状态:', status);
    return api.put(`/logistics/${id}/status`, { status });
  },

  // 查询物流轨迹
  trackLogistics(logisticsNumber) {
    console.log('调用查询物流轨迹API，物流单号:', logisticsNumber);
    return api.get(`/logistics/track/${logisticsNumber}`);
  },

  // 打印物流面单
  printShippingLabel(id) {
    console.log('调用打印物流面单API，ID:', id);
    return api.get(`/logistics/print/${id}`, { responseType: 'blob' });
  }
};

// 支付管理API
export const paymentAPI = {
  // 处理支付请求
  processPayment(paymentData) {
    return api.post('/payment/pay', paymentData);
  },

  // 获取支付方式
  getPaymentMethods() {
    return api.get('/payment/methods');
  },

  // 模拟支付回调
  mockPaymentCallback(callbackData) {
    return api.post('/payment/callback', callbackData);
  }
};

// 溯源统计API
export const traceStatsAPI = {
  // 获取基本统计数据
  getBasicStats() {
    return api.get('/api/trace-stats/basic');
  },

  // 获取最近溯源查询记录
  getRecentQueries(count = 10) {
    return api.get(`/api/trace-stats/recent-queries?count=${count}`);
  },

  // 获取查询趋势数据
  getQueryTrend(days) {
    return api.get(`/api/trace-stats/query-trend?days=${days}`);
  },

  // 获取查询地区分布数据
  getQueryRegionDistribution() {
    return api.get('/api/trace-stats/region-distribution');
  },

  // 获取产品查询排行
  getProductQueryRanking(count = 10) {
    return api.get(`/api/trace-stats/product-ranking?count=${count}`);
  },

  // 获取设备类型分布
  getDeviceTypeDistribution() {
    return api.get('/api/trace-stats/device-distribution');
  },

  // 获取浏览器分布
  getBrowserDistribution() {
    return api.get('/api/trace-stats/browser-distribution');
  },

  // 获取操作系统分布
  getOsDistribution() {
    return api.get('/api/trace-stats/os-distribution');
  }
};

export default {
  auth: authAPI,
  user: userAPI,
  farmer: farmerAPI,
  dealer: dealerAPI,
  product: productAPI,
  traceInfo: traceInfoAPI,
  traceQuery: traceQueryAPI,
  order: orderAPI,
  customer: customerAPI,
  statistics: statisticsAPI,
  farming: farmingAPI,
  distribution: distributionAPI,
  traceCode: traceCodeAPI,
  dashboard: dashboardAPI,
  role: roleAPI,
  permission: permissionAPI,
  menu: menuAPI,
  dict: dictAPI,
  log: logAPI,
  trace: traceAPI,
  logistics: logisticsAPI,
  payment: paymentAPI,
  traceStats: traceStatsAPI
};


